package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollUtil;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.FriendMovement;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.MyMovement;
import com.itheima.service.mongo.FriendService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import com.mongodb.client.result.DeleteResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class FriendServiceImpl implements FriendService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public void addContact(Long userId, Long friendId) {
        //1.当前用户添加对方为好友,将我的动态存入对方的好友动态表中
       if(!isFriend(userId,friendId)){
           addFriendAndMovement(userId,friendId);
       }

        //2.镜像操作(对方添加当前用户为好友,将对方的动态存放当前用户的好友动态中)
        if(!isFriend(friendId,userId)){
            addFriendAndMovement(friendId,userId);
        }
    }

    @Override
    public PageBeanVo findContactsByPage(Long userId, Integer pageNum, Integer pageSize) {
        //1.创建条件对象(userId)
        Query query = new Query(Criteria.where("userId").is(userId));

        //2.查询好友表中我的好友数量
        long count = mongoTemplate.count(query, Friend.class);

        //3.添加分页和排序
        query.with(Sort.by(Sort.Order.desc("created")))
             .skip((pageNum-1)*pageSize).limit(pageSize);

        //4.查询当前页的好友list
        List<Friend> friends = mongoTemplate.find(query, Friend.class);

        //5.封装PageBeanVo且返回
        return new PageBeanVo(pageNum,pageSize,count,friends);
    }

    //删除好友信息
    @Override
    public void delete(Long userId, Long friendId) {
        //1.删除自己的好友信息
        deleteFriend(userId, friendId);

        //2.删除好友的数据
        deleteFriend(friendId,userId);
    }



    //按id查询好友关系
    @Override
    public Boolean findByUserIdAndFriendId(Long userId, Long friendId) {
        Criteria criteria = Criteria.where("userId")
                .is(userId)
                .and("friendId")
                .is(friendId);
        Query query = Query.query(criteria);
        return mongoTemplate.exists(query, Friend.class);
    }

    @Override
    public PageBeanVo contactsListByUserId(Integer page, Integer pagesize, Long id) {
        Query query = new Query(Criteria.where("userId").is(id));

        //query.with(new Sort(Sort.Direction.DESC, "created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        long count = mongoTemplate.count(query, Friend.class);
        PageBeanVo pageBeanVo = new PageBeanVo(page, pagesize, count, friendList);
        return pageBeanVo;
    }

    @Override
    public Integer count(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, Friend.class);
        return Math.toIntExact(count);
    }

    private void deleteFriend(Long userId, Long friendId) {
        Query query = new Query(Criteria.where("userId").is(userId)
                .and("friendId").is(friendId));
        if (mongoTemplate.exists(query,Friend.class)){
            mongoTemplate.remove(query, Friend.class);
        }
    }



    private void addFriendAndMovement(Long userId, Long friendId) {
        //A.添加好友
        Friend friend = new Friend();
        friend.setUserId(userId);
        friend.setFriendId(friendId);
        friend.setCreated(System.currentTimeMillis());

        mongoTemplate.save(friend);

        //B.将我的动态存入对方的好友动态表中
        //1.查询我的动态列表
        List<MyMovement> myMovements = mongoTemplate.findAll(MyMovement.class, ConstantUtil.MOVEMENT_MINE + userId);

        //2.遍历我的动态列表,获取每个我的动态,将动态封装成好友动态,存入对方的好友动态表中
        if (CollUtil.isNotEmpty(myMovements)) {
            myMovements.forEach(myMovement -> {
                //将我的动态封装成好友动态
                FriendMovement friendMovement = new FriendMovement();
                friendMovement.setUserId(userId);
                friendMovement.setPublishId(myMovement.getPublishId());
                friendMovement.setCreated(myMovement.getCreated());

                //存入对方的好友动态表中
                mongoTemplate.save(friendMovement,ConstantUtil.MOVEMENT_FRIEND+friendId);
            });
        }
    }

    @Override
    public Boolean isFriend(Long userId, Long friendId) {
        Query query = new Query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        long count = mongoTemplate.count(query, Friend.class);
        return count==0?false:true;
    }

    @Override
    public void removeFriend(Long userId, Long loveId) {
        Query query1 = new Query(Criteria.where("userId").is(userId).and("friendId").is(loveId));
        mongoTemplate.remove(query1,Friend.class);


        Query query2 = new Query(Criteria.where("userId").is(loveId).and("friendId").is(userId));
        mongoTemplate.remove(query2,Friend.class);
    }

    @Override
    public void removeContacts(Long userId, Long friendId) {
        // 删除互相好友
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId)), Friend.class);
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(friendId).and("friendId").is(userId)), Friend.class);
        // 删除好友后互相删除存储的彼此的动态信息
        DeleteResult userId1 = mongoTemplate.remove(Query.query(Criteria.where("userId").is(userId)), ConstantUtil.MOVEMENT_FRIEND + friendId);
        DeleteResult userId2 = mongoTemplate.remove(Query.query(Criteria.where("userId").is(friendId)), ConstantUtil.MOVEMENT_FRIEND + userId);
        System.out.println(userId1 + "" + userId2);
    }
}
